﻿@page "/form"

@using System.ComponentModel.DataAnnotations
@using System.Reflection

<PageTitle>表单</PageTitle>
<h2>表单与验证</h2>

<button class="btn btn-primary" @onclick=Submit>提交</button>

<EditForm EditContext="Context">
    <DataAnnotationsValidator/>
    <div class="row mb-3">
        <label class="col-1 col-form-label">姓名：</label>
        <div class="col-11">
            <InputText @bind-Value="Model.Name" class="form-control" />
        </div>
    </div>
    <div class="row mb-3">
        <label class="col-1 col-form-label">密码：</label>
        <div class="col-11">
            <InputText @bind-Value="Model.Password" class="form-control" type="password" />
        </div>
    </div>
</EditForm>

@if (_isSubmitted)
{
    <div class="alert alert-success">
        <ul>
            <li>姓名：@Model.Name</li>
            <li>密码：@Model.Password</li>
        </ul>
    </div>
}

@if (Errors.Any())
{
    <div class="alert alert-danger">
        <ul>
            @foreach (var message in Errors)
            {
                <li>@message</li>
            }
        </ul>
    </div>
}

@GetValidation(nameof(Model.Name))


@code {
    class UserInfo
    {
        [Required(ErrorMessage ="名字不能为空")]        
        public string? Name { get; set; }

        [Required(ErrorMessage = "密码不能为空")]
        public string? Password { get; set; }
    }

    EditContext Context { get; set; }

    IEnumerable<string> Errors { get; set; } = [];


    public Form()
    {
        Context = new EditContext(Model);
        Context.SetFieldCssClassProvider(new FormCssClassProvider());
    }

    UserInfo Model = new();

    bool _isSubmitted;

    Task Submit()
    {
        var valid= Context.Validate();
        if (!valid)
        {
            Errors = Context.GetValidationMessages();
            return Task.CompletedTask;
        }

        _isSubmitted = true;
        return Task.CompletedTask;
    }

    string? GetValidation(string name)
    {
        var fieldIdentifier = Context.Field(name);
        if (!Context.IsValid(fieldIdentifier))
        {
            var property = Model?.GetType()?.GetProperty(fieldIdentifier.FieldName);

            var requiredAttr = property?.GetCustomAttribute<RequiredAttribute>();
            var value = property?.GetValue(Model);

            if (!requiredAttr.IsValid(value))
            {
                return requiredAttr.ErrorMessage;
            }
        }
        return string.Empty;
    }
}
